<template>
  <u-upload
    :file-list="fileList1"
    name="1"
    multiple
    :max-count="10"
    @afterRead="afterRead"
    @delete="deletePic"
  ></u-upload>
</template>

<script setup>
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  // renderOptions: {
  //   required: true,
  //   type: Array,
  //   default: () => [],
  // },
  // renderData: {
  //   required: true,
  //   type: Object,
  // },
  // requestUrl: {
  //   // 业务场景请求地址
  //   required: true,
  //   type: String,
  // },
  // moduleCode: {
  //   // 业务场景编码
  //   required: true,
  //   type: String,
  // },
  // rules: {
  //   type: Object,
  //   default: () => {},
  // },
})
import { ref } from 'vue'
const uploadPool = ref([])
const fileList1 = ref([])
const emit = defineEmits(['change', 'update:modelValue'])
// 删除图片
const deletePic = (event) => {
  fileList1.value.splice(event.index, 1)
}
// const apiURL = import.meta.env.VITE_BASE_API
// console.log(import.meta.env.VITE_API_URL)
// 新增图片
const afterRead = async (event) => {
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file)
  let fileListLen = fileList1.value.length
  lists.map((item) => {
    fileList1.value.push({
      ...item,
      status: 'uploading',
      message: '上传中',
    })
  })
  for (let i = 0; i < lists.length; i++) {
    const result = await uploadFilePromise(lists[i].url)
    let item = fileList1.value[fileListLen]
    fileList1.value.splice(fileListLen, 1, {
      ...item,
      status: 'success',
      message: '',
      url: result,
    })
    fileListLen++
  }
}
const token = uni.getStorageSync('token')
const token_type = uni.getStorageSync('token_type')
const uploadFilePromise = (url) => {
  return new Promise((resolve, reject) => {
    let a = uni.uploadFile({
      url: 'http://192.168.0.62:9999/zgyp-system/api/v1/files', // 仅为示例，非真实的接口地址
      header: {
        Authorization: `${token_type} ` + `${token}`,
      },
      filePath: url,
      name: 'file',
      formData: {},
      success: (res) => {
        setTimeout(() => {
          resolve(res.data.data)
          const urldata = JSON.parse(res.data).data
          console.log(urldata)
          uploadPool.value.push(urldata.url)
          emit('update:modelValue', uploadPool.value.join(','))
          emit('change', uploadPool.value.join(','))
        }, 1000)
      },
    })
  })
}
</script>
